package controllers;

import java.util.ArrayList;
import java.util.List;

import com.ebay.sdk.ApiException;
import com.ebay.sdk.SdkException;
import com.ebay.services.finding.Amount;
import com.ebay.services.finding.SearchItem;
import com.ebay.soap.eBLBaseComponents.CatalogProductType;
import com.ebay.soap.eBLBaseComponents.ExternalProductCodeType;
import com.ebay.soap.eBLBaseComponents.ExternalProductIDType;
import com.ebay.soap.eBLBaseComponents.ItemType;
import com.ebay.soap.eBLBaseComponents.NameValueListType;

import play.data.validation.Required;
import play.mvc.*;

public class Search extends Controller {
    public static void index() {
        render();
    }
    
    public static void search(@Required String searchByKeyword) throws ApiException, SdkException, Exception{
    	Api api = new Api();
	//	String output = "";
		if (api.buyerSearchByKeywordFindingApi(searchByKeyword)==null) {
			renderText("it dose not work");
		} else {
			List<SearchItem> searchItems;
			List<SearchItem> searchReturnItems = new ArrayList();
			searchItems = api.buyerSearchByKeywordFindingApi(searchByKeyword);	
			for(int i =0;i<searchItems.size();i++){			
				Amount amount = new Amount();
				String isbn = api.getItemsByItemID(searchItems.get(i).getItemId()).getProductListingDetails().getISBN();
				searchItems.get(i).setGalleryURL("http://covers.openlibrary.org/b/isbn/"+isbn+"-M.jpg");
				double price = api.getItemsByItemID(searchItems.get(i).getItemId()).getStartPrice().getValue();
				amount.setValue(price);
				searchItems.get(i).getListingInfo().setBuyItNowPrice(amount);	
				
				
			}
			String user = Security.connected();
			render(user, searchItems);
		}
		
    }
    
    public static void searchDetails(@Required String itemID) throws ApiException, SdkException, Exception{
    	Api api = new Api();
    	String details = null;
    	ItemType itemType = api.getItemsByItemID(itemID);       
  /*  	if(itemType.getExternalProductID()==null){
    		ExternalProductIDType type = new ExternalProductIDType();
    		type.setType(ExternalProductCodeType.ISBN);
    		type.setValue("9780307473479");
    		itemType.setExternalProductID(type);
    	}
   */ 
    	String isbn = itemType.getProductListingDetails().getISBN();
    	if(itemType.getItemSpecifics()!=null){
    	details =itemType.getItemSpecifics().toString();
    	}
    	String user = Security.connected();
    	render(user, itemType,details, isbn);
    	
    }
    

}
